package com.jiang.sign.Service.impl;

import com.alibaba.fastjson.JSONObject;
import com.jiang.sign.Dao.LoginUser;
import com.jiang.sign.Dao.SignUser;
import com.jiang.sign.Redis.RedisCache;
import com.jiang.sign.Service.SignService;
import com.jiang.sign.Utils.JwtUtil;
import org.springframework.security.authentication.AuthenticationManager;

import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Objects;

@Service
public class SignServiceImpl implements SignService {

   @Resource
   private AuthenticationManager authenticationManager;
   @Resource
   private RedisCache redisCache;

    @Override
    public JSONObject login(JSONObject jsonObject) {
        //AuthenticationManager authenticate 进行用户认证
        JSONObject jso = new JSONObject();
        Object username = jsonObject.get("username");
        Object password = jsonObject.get("password");
        UsernamePasswordAuthenticationToken authenticationToken =new UsernamePasswordAuthenticationToken(username,password,null);
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);
        //如果没有认证通过，给出对应的提示
        if(Objects.isNull(authenticate)){
            throw new RuntimeException("登录失败");
        }
        //如果认证通过了，使用userid生成一个jwt  jwt存入json返回
        LoginUser loginUser = (LoginUser)authenticate.getPrincipal();
        //这里的id存入的时候可以用雪花id
        String userid = loginUser.getSignUser().getId().toString();
        String jwt = JwtUtil.createJWT(userid);
        jso.fluentPut("Success","200").fluentPut("token",jwt);
        //把完整的用户信息存入redis userid作为key
        redisCache.setCacheObject("login:"+userid,loginUser);
        return jso;
    }

    @Override
    public JSONObject loginout() {
        JSONObject jsonObject = new JSONObject();
        //获取SecurityContextHolder中的用户信息
        UsernamePasswordAuthenticationToken authenticationToken = (UsernamePasswordAuthenticationToken)SecurityContextHolder.getContext().getAuthentication();
        LoginUser loginUser = (LoginUser) authenticationToken.getPrincipal();
        String userid  = loginUser.getSignUser().getId().toString();
        //删除redis中的值
          redisCache.deleteObject("login:"+userid);
        jsonObject.fluentPut("Success","200");
        return jsonObject;
    }


}
